package util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ResourceUtil {
    /**
     * 获取静态资源的绝对路径
     *
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) {
        String absolutePath = ResourceUtil.class.getResource("/").getPath();
        path = absolutePath.replace("\\\\", "/") + path;
        return path.replaceAll("//", "/");
    }

    public static void outputStaticeResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int resourceSize = 0;
        while (resourceSize == 0) {
            resourceSize = inputStream.available();
        }

        //输出http请求头
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());
        //在输出具体内容
        long written = 0;//已读取的内容
        int byteSize = 1024;//计划缓冲长度
        byte[] bytes = new byte[byteSize];
        while (written < resourceSize) {
            if (written + byteSize > resourceSize) { //未读内容少于一个1024长度
                byteSize = (int) (resourceSize - written); //剩余文件内容长度
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            written += byteSize;
        }
    }
}
